package team.pra.manager.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.pra.manager.common.PageHelper;
import team.pra.manager.service.CheckinService;
import team.pra.manager.common.ManagerResult;
import team.pra.manager.common.PageBean;
import team.pra.manager.mapper.CheckinMapper;
import team.pra.manager.pojo.Checkin;

import java.util.List;

@Service
public class CheckinServiceImpl implements CheckinService {

    @Autowired(required = false)
    private CheckinMapper checkinMapper;

    @Override
    public PageBean<Checkin> queryByPage(int code, int size) {
        PageBean<Checkin> pageBean = new PageBean<>();
        pageBean.setCode((code-1)*size);
        pageBean.setSize(size);
        List<Checkin> checkins = checkinMapper.queryByPage(pageBean);
        pageBean.setRows(checkins);
        Integer totalCheckins = checkinMapper.countCheckinNumber();
        Integer total = 1;
        if (totalCheckins % size != 0) {
            total = totalCheckins/size + 1;
        }else {
            total = totalCheckins/size;
        }
        pageBean.setTotal(total);
        return pageBean;
    }

    @Override
    public List<Checkin> queryAll() {
        return checkinMapper.queryAll();
    }

    @Override
    public Checkin queryById(Integer id) {
        return checkinMapper.queryById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ManagerResult update(Checkin checkin) {
        Boolean result = checkinMapper.update(checkin);
        return ManagerResult.ok(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ManagerResult insert(Checkin checkin) {
        Boolean result = checkinMapper.insert(checkin);
        return ManagerResult.ok(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ManagerResult delete(Integer id) {
        Boolean result = checkinMapper.delete(id);
        return ManagerResult.ok(result);
    }

    @Override
    public void findCheckinByCondition(PageHelper<Checkin> pageHelper) {
        pageHelper.setData(checkinMapper.findCheckinByCondition(pageHelper));
        pageHelper.setRecordsTotal(checkinMapper.countCheckinNumber());
        pageHelper.setRecordsFiltered(checkinMapper.filteredCheckin(pageHelper));
    }
}
